package com.itboye.mengwu.app.ui.aiwujia;

import java.io.File;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import com.itboye.core.alert.ByAlert;
import com.itboye.core.object.BaseActivity;
import com.itboye.core.object.ResultEntity;
import com.itboye.core.object.SpPublicParams;
import com.itboye.core.utils.ImageCompressAndUpload;
import com.itboye.core.utils.SPUtils;
import com.itboye.core.utils.YesNoPopupWindow;
import com.itboye.core.utils.ImageCompressAndUpload.OnUploadlistener;
import com.itboye.mengwu.R;
import com.itboye.mengwu.app.ui.main.PingLunBaoBeiActivity;
import com.itboye.mengwu.app.ui.main.PingLunBaoBeiActivity.PopupWindows;
import com.itboye.mengwu.app.ui.mymeng.ActivityBabyEdit;
import com.itboye.mengwu.data.model.LuntanTieZiBean;
import com.itboye.mengwu.data.model.MaMaZengFaBuFenLeiBean;
import com.itboye.mengwu.data.presenter.NewMaMaZengPresenter;
import com.itboye.mengwu.data.presenter.TieZiPresenter;
import com.itboye.mengwu.luntan.comment.adapter.GridViewAdapter;
import com.itboye.mengwu.testpic.ui.Bimp;
import com.itboye.mengwu.testpic.ui.FileUtils;
import com.itboye.mengwu.testpic.ui.PhotoActivity;
import com.itboye.mengwu.widget.MyGridView;
import com.itboye.mengwu.widget.PhotoSelectFragment;
import com.itboye.mengwu.widget.PhotoSelectFragment.PhotoSelectListener;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class ActivityMaMaZengPingLunBaoBei extends BaseActivity implements
		Observer {
	private MyGridView aiWuJiaGridView;
	private GridViewAdapter adapter;
	// private TextView activity_selectimg_send;
	// private ImageView imgPublishBack;
	NewMaMaZengPresenter newMaMaZengPresenter;
	RelativeLayout zengsongmengbiLine;
	MengBiPopupWindow mengBiPopupWindow;

	// 标题
	private EditText edttitle;
	// 内容
	private EditText edtcontext;
	// private String title;
	private String contextEd;
	TextView txt_save;

	public final static int HU = 1;
	TextView ask, share;

	ImageView back;
	TextView txt_title, txt_cancel, mengbiTv;
	Button btn_ok;
	ArrayList<String> imgUrls = new ArrayList<>();

	String type, pid;

	RatingBar miaoshuRb, wuliuRb, zengsongRb;

	public ActivityMaMaZengPingLunBaoBei() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public int initView() {
		// TODO Auto-generated method stub
		return R.layout.activity_mamazengpinglunbaobei;
	}

	@Override
	public void onMyCreate() {
		// tanPresenter = new TieZiPresenter(this);
		newMaMaZengPresenter = new NewMaMaZengPresenter(this);

		// xiangfuRb= findViewById(R.id.xiangf)
		Intent intent = getIntent();
		pid = intent.getStringExtra("pid");
		back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		zengsongmengbiLine.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				mengBiPopupWindow = new MengBiPopupWindow(
						ActivityMaMaZengPingLunBaoBei.this, onclicklister);
				mengBiPopupWindow.showAtLocation(v, Gravity.BOTTOM
						| Gravity.CENTER_HORIZONTAL, 0, 0);
			}
		});

		txt_title.setText("评论宝贝");
		txt_cancel.setText("发布");
		Init();

	}

	private StringBuffer attachments;
	protected ArrayList<String> uploadedUrl = new ArrayList<String>();

	public void Init() {
		// aiWuJiaGridView = (MyGridView) findViewById(R.id.aiWuJiaGridView);
		// aiWuJiaGridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
		// adapter = new GridAdapter(this);
		// adapter.update();
		// aiWuJiaGridView.setAdapter(adapter);
		//
		type = getIntent().getStringExtra("type");
		adapter = new GridViewAdapter(this, imgUrls);
		aiWuJiaGridView.setAdapter(adapter);
		aiWuJiaGridView.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				if (arg2 == imgUrls.size()) {
					new PopupWindows(ActivityMaMaZengPingLunBaoBei.this,
							aiWuJiaGridView);
				} else {
					Intent intent = new Intent(
							ActivityMaMaZengPingLunBaoBei.this,
							PhotoActivity.class);
					intent.putExtra("imgUrls", imgUrls);
					intent.putExtra("ID", arg2);
					startActivity(intent);
				}
			}
		});

		txt_cancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				contextEd = edtcontext.getText() + "";
				if (contextEd == null || contextEd == "") {
					ByAlert.alert("请输入内容");
					return;
				}
				onBitMap();
			}
		});
	}

	public void onBitMap() {
		List<String> list = new ArrayList<String>();
		for (int i = 0; i < imgUrls.size(); i++) {
			String Str = imgUrls.get(i).substring(
					imgUrls.get(i).lastIndexOf("/") + 1,
					imgUrls.get(i).lastIndexOf("."));
			list.add(FileUtils.SDPATH + Str + ".JPEG");
		}

		// 高清的压缩图片全部就在 list 路径里面了
		// 高清的压缩过的 bmp 对象 都在 Bimp.bmp里面
		// 完成上传服务器后 .........

		// title = edttitle.getText().toString().trim();

		// final TieZiPresenter tanPresenter = new TieZiPresenter(this);

		if (imgUrls.size() > 0) {
			for (int j = 0; j < imgUrls.size(); j++) {
				// System.out.println("路径" + Bimp.drr.get(j));
				ImageCompressAndUpload.getInstance().execute(imgUrls.get(j),
						new OnUploadlistener() {

							@Override
							public void OnSuccess(String resultData) {
								uploadedUrl.add(resultData);
								System.out.println("rse" + resultData);
								if (uploadedUrl.size() == imgUrls.size()) {
									if (uploadedUrl.size() > 0) {

										attachments = new StringBuffer();
										attachments.append(uploadedUrl.get(0));
										for (int i = 1; i < uploadedUrl.size(); i++) {
											attachments.append(",").append(
													uploadedUrl.get(i));
										}

									}
									LuntanTieZiBean bean = new LuntanTieZiBean();
									bean.setUid((String) SPUtils.get(
											ActivityMaMaZengPingLunBaoBei.this,
											null, SpPublicParams.UID, ""));
									// bean.setSubject(title);
									bean.setMessage(contextEd);
									bean.setAuthor((String) SPUtils.get(
											ActivityMaMaZengPingLunBaoBei.this,
											null, SpPublicParams.NICK_NAME, ""));
									bean.setFid(1 + "");
									bean.setTypeid(1 + "");
									bean.setAttachments(attachments);
									Log.e("uid", (String) SPUtils.get(
											ActivityMaMaZengPingLunBaoBei.this,
											null, SpPublicParams.UID, ""));
									Log.e("pid", pid);
									Log.e("contextEd", contextEd);
									Log.e("xiangfuRb.getNumStars() ",
											miaoshuRb.getRating() + "");
									Log.e("wuliuRb.getNumStars() ",
											wuliuRb.getRating() + "");
									Log.e("zengsongRb.getNumStars() ",
											zengsongRb.getRating() + "");
									Log.e("attachments ", attachments + "");

									newMaMaZengPresenter.pingjia(
											(String) SPUtils
													.get(ActivityMaMaZengPingLunBaoBei.this,
															null,
															SpPublicParams.UID,
															""), pid,
											contextEd, miaoshuRb.getRating()
													+ "", wuliuRb.getRating()
													+ "",
											zengsongRb.getRating() + "",
											attachments + "", mengbiTv
													.getText().toString()
													.substring(0, 3)
													+ "");
									// tanPresenter.add(bean);

								}

							}

							@Override
							public void OnError(String resultData) {
								ByAlert.alert("发表出错了╰(￣▽￣)╭");
								// toast.show();
							}
						}, "bbs");
			}
		} else {
			LuntanTieZiBean bean = new LuntanTieZiBean();
			bean.setUid((String) SPUtils.get(
					ActivityMaMaZengPingLunBaoBei.this, null,
					SpPublicParams.UID, ""));
			// bean.setSubject(title);
			bean.setMessage(contextEd);
			bean.setAuthor((String) SPUtils.get(
					ActivityMaMaZengPingLunBaoBei.this, null,
					SpPublicParams.NICK_NAME, ""));
			bean.setFid(1 + "");
			bean.setTypeid(1 + "");
			bean.setAttachments(null);

			newMaMaZengPresenter.pingjia((String) SPUtils.get(
					ActivityMaMaZengPingLunBaoBei.this, null,
					SpPublicParams.UID, ""), pid, contextEd,
					miaoshuRb.getNumStars() + "", wuliuRb.getNumStars() + "",
					zengsongRb.getNumStars() + "", attachments + "", mengbiTv
							.getText().toString().substring(0, 3)
							+ "");
			// tanPresenter.add(bean);
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	public class PopupWindows extends PopupWindow {

		public PopupWindows(Context mContext, View parent) {

			View view = View
					.inflate(mContext, R.layout.item_popupwindows, null);
			view.startAnimation(AnimationUtils.loadAnimation(mContext,
					R.anim.fade_ins));
			LinearLayout ll_popup = (LinearLayout) view
					.findViewById(R.id.ll_popup);
			ll_popup.startAnimation(AnimationUtils.loadAnimation(mContext,
					R.anim.push_bottom_in_2));

			setWidth(LayoutParams.FILL_PARENT);
			setHeight(LayoutParams.FILL_PARENT);
			setBackgroundDrawable(new BitmapDrawable());
			setFocusable(true);
			setOutsideTouchable(true);
			setContentView(view);
			showAtLocation(parent, Gravity.BOTTOM, 0, 0);
			update();

			Button bt1 = (Button) view
					.findViewById(R.id.item_popupwindows_camera);
			Button bt2 = (Button) view
					.findViewById(R.id.item_popupwindows_Photo);
			Button bt3 = (Button) view
					.findViewById(R.id.item_popupwindows_cancel);
			bt1.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					photo();
					dismiss();
				}
			});
			bt2.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					new PhotoSelectFragment(new PhotoSelect(), 9).show(
							getSupportFragmentManager(), null);
				}
			});
			bt3.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					dismiss();
				}
			});

		}
	}

	class PhotoSelect implements PhotoSelectListener {

		@Override
		public void onPhotoSelectFinish(List<String> paths) {
			for (String string : paths) {
				// XImageLoader.load("file://" + string,
				// (ImageView) v.findViewById(R.id.img));
				imgUrls.add(string);

			}
			adapter.notifyDataSetChanged();
		}

	}

	private static final int TAKE_PICTURE = 0x000000;
	private String path = "";
	public String addr;

	public void photo() {
		Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		File file = new File(Environment.getExternalStorageDirectory()
				+ "/myimage/", String.valueOf(System.currentTimeMillis())
				+ ".jpg");
		path = file.getPath();
		Uri imageUri = Uri.fromFile(file);
		openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
		startActivityForResult(openCameraIntent, TAKE_PICTURE);
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case TAKE_PICTURE:
			if (Bimp.drr.size() < 9 && resultCode == -1) {
				Bimp.drr.add(path);
			}
			break;
		}
	}

	@Override
	public void update(Observable observable, Object data) {
		// TODO Auto-generated method stub
		ResultEntity entity = handlerError(data);
		if (entity != null) {
			if (entity.getEventType() == NewMaMaZengPresenter.PingjiaSuccess) {
				String str = (String) entity.getData();
				ByAlert.alert(str);
			} else if (entity.getEventType() == NewMaMaZengPresenter.PingjiaFail) {
				ByAlert.alert("评价失败");
			}

		}
		edtcontext.setText("");
		// edttitle.setText("");
		Bimp.bmp.clear();
		finish();
		adapter.notifyDataSetChanged();
	}

	public class MengBiPopupWindow extends PopupWindow {
		private TextView mengbi100_tv, mengbi200_tv, mengbi300_tv, cancel_tv;
		private View sexMenuView;

		public MengBiPopupWindow(Activity context, OnClickListener itemOnclick) {
			super(context);
			LayoutInflater layoutInflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			sexMenuView = layoutInflater.inflate(
					R.layout.mamazengpinglun_dialog, null);
			// yes_tv = (TextView) sexMenuView.findViewById(R.id.yes_tv);
			// no_tv = (TextView) sexMenuView.findViewById(R.id.no_tv);
			mengbi100_tv = (TextView) sexMenuView
					.findViewById(R.id.mengbi100_tv);
			mengbi200_tv = (TextView) sexMenuView
					.findViewById(R.id.mengbi200_tv);
			mengbi300_tv = (TextView) sexMenuView
					.findViewById(R.id.mengbi300_tv);
			cancel_tv = (TextView) sexMenuView.findViewById(R.id.cancel_tv);

			cancel_tv.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					dismiss();// ȡ��
				}
			});
			mengbi100_tv.setOnClickListener(itemOnclick);
			mengbi200_tv.setOnClickListener(itemOnclick);
			mengbi300_tv.setOnClickListener(itemOnclick);
			// ����popupwindow��view
			this.setContentView(sexMenuView);
			// ����popupwindow��view�Ŀ��
			this.setWidth(LayoutParams.FILL_PARENT);
			// ����popupwindow��view�ĸ߶�
			this.setHeight(LayoutParams.WRAP_CONTENT);
			// ����PopupWindow��������ɵ��
			this.setFocusable(true);
			// ����PopupWindow�������嶯��Ч��
			this.setAnimationStyle(R.style.AnimBottom);
			// ʵ����һ����ɫ
			ColorDrawable dw = new ColorDrawable(0xb000000);
			// ����popupwindow������������ɫ
			this.setBackgroundDrawable(dw);
			// mMenuView���OnTouchListener�����жϻ�ȡ����λ�������ѡ������������ٵ�����
			sexMenuView.setOnTouchListener(new OnTouchListener() {

				@Override
				public boolean onTouch(View v, MotionEvent event) {
					int height = sexMenuView.findViewById(R.id.sex_layout)
							.getTop();
					int y = (int) event.getY();
					if (event.getAction() == MotionEvent.ACTION_UP) {
						if (y < height) {
							dismiss();
						}
					}

					return true;
				}
			});
		}
	}

	private OnClickListener onclicklister = new OnClickListener() {
		@Override
		public void onClick(View view) {
			// TODO Auto-generated method stub
			switch (view.getId()) {
			case R.id.mengbi100_tv:
				mengbiTv.setText("100萌币");
				mengBiPopupWindow.dismiss();
				ByAlert.alert(mengbiTv.getText().toString().substring(0, 3));
				break;
			case R.id.mengbi200_tv:
				mengbiTv.setText("200萌币");
				mengBiPopupWindow.dismiss();
				ByAlert.alert(mengbiTv.getText().toString().substring(0, 3));
				break;
			case R.id.mengbi300_tv:
				mengbiTv.setText("300萌币");
				mengBiPopupWindow.dismiss();
				ByAlert.alert(mengbiTv.getText().toString().substring(0, 3));
				break;
			default:
				break;
			}
		}

	};

}
